package com.zzq.base.awesome.api.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzq.base.awesome.api.entity.User;
import com.zzq.base.awesome.api.service.UserService;
import com.zzq.base.awesome.component.RoleComponent;
import com.zzq.base.awesome.component.UserCache;
import com.zzq.base.awesome.entity.*;
import com.zzq.base.awesome.utils.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.zzq.base.awesome.controller.BaseController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.zzq.base.awesome.entity.CommonData.TOKENTAG;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 赵自强
 * @since 2020-02-09
 */
@RestController
@RequestMapping("/api/user")
@Slf4j
public class UserController extends BaseController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserCache userCache;

    @PostMapping("/login")
    private Result<User> login(@RequestParam String userName, @RequestParam String password,
                               HttpServletResponse response) {
        if (StringUtils.isEmpty(userName)) {
            return Result.buildParamEmptyError();
        }
        log.info("find User: " + userName);
        User user = userService.getUserOnLogin(userName);
        if (user == null) {
            return Result.buildUserNotExistError();
        }
        if (userService.isPasswordOk(user, password)) {
            String token = JwtTokenUtils.getJwtTokenWithOutBarer(user.getSign());
            response.addHeader(TOKENTAG, token);
            userCache.putUserInCache(user);
            return Result.buildSuccess(user);
        }
        return Result.buildError("密码不正确");
    }

    @PostMapping("/register")
    private Result<User> register(@RequestBody RequestEntity.RegisterData registerData) {
        log.info("register: " + registerData);
        String account = registerData.getAccount();
        String mail = registerData.getMail();
        String password = registerData.getPassword();
        String mobile = registerData.getMobile();
        String userName = registerData.getUserName();
        if (!userService.isCanRegister(account, mail, password, mobile, userName)) {
            return Result.buildParamEmptyError();
        }
        if (userService.haveSameUser(account, mail, mobile)) {
            return Result.buildError("注册信息已经存在 不可以重复注册");
        }
        String avatarName = SystemUtils.getUUID();
        try {
            CreateNamePicture.generateImg(userName, SingleObject.avatarPath, avatarName);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.buildError("生成头像出现错误");
        }
        User user = new User();
        user.setAvatar("avatar/" + avatarName + CommonData.IMGSUFFIX);
        user.setPassword(password);
        user.setTelephone(mobile);
        user.setEmail(mail);
        user.setAccount(account);
        user.setUsername(userName);
        if (userService.save(user)) {
            log.info("注册用户: {}" , user);
            return Result.buildSuccess(user);
        }
        return Result.buildDatabaseError();
    }


    @PostMapping("/add")
    private Result<User> add(@RequestBody RequestEntity.AddData addData) {
        log.info("add: " + addData);
        String account = addData.getAccount();
        String mail = addData.getMail();
        String password = addData.getPassword();
        String mobile = addData.getMobile();
        String userName = addData.getUserName();
        if (!userService.isCanRegister(account, mail, password, mobile, userName)) {
            return Result.buildParamEmptyError();
        }
        if (userService.haveSameUser(account, mail, mobile)) {
            return Result.buildError("注册信息已经存在 不可以重复添加");
        }
        String avatarName = SystemUtils.getUUID();
        try {
            CreateNamePicture.generateImg(userName, SingleObject.avatarPath, avatarName);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.buildError("生成头像出现错误");
        }
        User user = new User();
        user.setAvatar("avatar/" + avatarName + CommonData.IMGSUFFIX);
        user.setPassword(password);
        user.setTelephone(mobile);
        user.setEmail(mail);
        user.setAccount(account);
        user.setUsername(userName);
        user.setType(addData.getType());
        if (userService.save(user)) {
            log.info("添加用户: {}" , user);
            return Result.buildSuccess(user);
        }
        return Result.buildDatabaseError();
    }

    @PostMapping("/update")
    private Result<User> upDate(@RequestParam int id,@RequestBody RequestEntity.AddData addData) {
        log.info("upDate: " + id);
        if (id == 1 && addData.getType() == 0) {
            return Result.buildError("超级管理员不能改变角色");
        }
        User user = userService.getById(id);
        if (user.getSignString().equals(addData.getSignString())) {
            log.info("没有对信息做出修改");
            return Result.buildError("没有对信息做出修改");
        }
        String account = addData.getAccount();
        String mail = addData.getMail();
        String password = addData.getPassword();
        String mobile = addData.getMobile();
        String userName = addData.getUserName();
        if (!userService.isCanRegister(account, mail, password, mobile, userName)) {
            return Result.buildParamEmptyError();
        }
        if (!userService.canUpdate(id,account, mail, mobile)) {
            return Result.buildError("更新的信息已经存在");
        }
        if (!user.getUsername().equals(addData.getUserName())) {
            String avatarName = SystemUtils.getUUID();
            try {
                CreateNamePicture.generateImg(userName, SingleObject.avatarPath, avatarName);
            } catch (IOException e) {
                e.printStackTrace();
                return Result.buildError("生成头像出现错误");
            }
            user.setAvatar("avatar/" + avatarName + CommonData.IMGSUFFIX);
        }
        user.setPassword(password);
        user.setTelephone(mobile);
        user.setEmail(mail);
        user.setAccount(account);
        user.setUsername(userName);
        user.setType(addData.getType());
        if (userService.updateById(user)) {
            log.info("更新用户: {}" , user);
            return Result.buildSuccess(user);
        }
        return Result.buildDatabaseError();
    }
    @GetMapping("/list")
    private Result<PageResult<User>> getAllUser(@RequestParam int pageSize, @RequestParam int pageNo) {
        log.info("获取用户列表第 {} 页, 此页 {} 条数据", pageNo, pageSize);
        IPage<User> userIPage = new Page<>(pageNo, pageSize);
        userIPage = userService.page(userIPage);
        PageResult<User> pageResult = PageResult.wrapIPage(userIPage);
        log.info("获取分页结果 {}", pageResult);
        return Result.buildSuccess(pageResult);
    }
    @Autowired
    private RoleComponent roleComponent;
    @GetMapping("/info")
    private Result<User> info() {
        String id = this.getUserId();
        log.info("用户id: {}", id);
        User user = userService.getById(id);
        if (user == null) {
            return Result.buildUserNotExistError();
        }
        user.setRole(roleComponent.getRole(user.getType()));
        return Result.buildSuccess(user);
    }



    @PostMapping("/logout")
    private Result<String> logout() {
        String id = this.getUserId();
        log.info("退出id: {}", id);
        userCache.removeUserFromCache(id);
        return Result.buildSuccess();
    }

    @GetMapping("/delete")
    private Result<String> delete(@RequestParam int id) {
        log.info("删除id: {}", id);
        if (id == 1) {
            return Result.buildError("超级管理员不可以删除");
        }
        boolean a = userService.removeById(id);
        if (a) {
            return Result.buildSuccess();
        }else {
            return Result.buildDatabaseError();
        }
    }

}
